import org.omg.CORBA.PUBLIC_MEMBER;

/**
 *
 * @param <K>
 * @param <V>
 */
public class HashBuck<K, V> {
    static class Node<K, V> {
        private K key;
        private V val;
        private Node<K, V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node<K, V>[] array = (Node<K, V>[]) new Node[10];

    public int usedSize;
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public void put(K key, V val) {
        Node<K, V> node = new Node<>(key, val);
        int hash = key.hashCode();
        int index = hash % array.length; // 控制成合理的位置
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        // cur == null 进行头插法
        node.next = array[index];
        array[index] = node;

        usedSize++;
        //计算负载因子

        if (loadFactor() >= DEFAULT_LOAD_FACTOR) {
            // 扩容
            resize();
        }
    }

    private float loadFactor() {
        return usedSize * 1.0f / array.length;
    }

    private void resize() {
        Node<K, V>[] tmpArray = (Node<K, V>[])new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node<K, V> cur = array[i];
            while (cur != null) {
                // 不记录链表后面的节点 就会找不到
                Node<K, V> curNext = cur.next;
                int index = cur.key.hashCode() % tmpArray.length;
                // 采用的是头插法
                cur.next = tmpArray[index];
                tmpArray[index] = cur;
                cur = curNext;
            }
        }
        array = tmpArray;
    }

    /**
     * 通过key来返回val
     * @param key
     */
    public V get(K key) {
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
